#include "GPIO_LED.hpp"

namespace DriverFramework
{

GPIOLED::GPIOLED() :
    DevObj("led", "/dev/gpio", LED_CLASS_PATH, DeviceBusType_UNKNOWN, 0)
{
    _gpioPin[0] = GPIO_A_LED_PIN;
    _gpioPin[1] = GPIO_B_LED_PIN;
    _gpioPin[2] = GPIO_C_LED_PIN;
    _gpioPin[3] = GPIO_D_LED_PIN;

    _gpioCnt = 0;
    for (size_t i = 0; i < 4; i++) {
        if (_gpioPin[i] > 0) {
            _gpio[i] = new GPIO(_gpioPin[i]);
            _gpio[i]->enable();
            _gpio[i]->setDirection(GPIO::OUTPUT);
            _gpioCnt++;
        }
    }
}

GPIOLED::~GPIOLED()
{
    for (int i = 0; i < _gpioCnt; i++) {
        _gpio[i]->disable();
        delete _gpio[i];
        _gpio[i] = nullptr;
    }
}

int
GPIOLED::init()
{
    DF_LOG_DEBUG("GPIOLED::init");
    int ret = DevObj::init();

    return ret;
}

int GPIOLED::on(int pinIndex)
{
    if (pinIndex>=0 && pinIndex<_gpioCnt) {
        return _gpio[pinIndex]->setValue(GPIO::HIGH);
    } else {
        return -1;
    }
}

int GPIOLED::off(int pinIndex)
{
    if (pinIndex>=0 && pinIndex<_gpioCnt) {
        return _gpio[pinIndex]->setValue(GPIO::LOW);
    } else {
        return -1;
    }
}

int GPIOLED::toggle(int pinIndex)
{
    if (pinIndex>=0 && pinIndex<_gpioCnt) {
        GPIO::VALUE val;
        int ret;
        ret = _gpio[pinIndex]->readValue(val);

        if (ret < 0) {
            return ret;
        }

        ret = (val == GPIO::LOW ? _gpio[pinIndex]->setValue(GPIO::HIGH)
                                : _gpio[pinIndex]->setValue(GPIO::LOW));

        return ret;

    } else {
        return -1;
    }
}

} //end namespace
